package com.lire.shop.controller;

import com.google.gson.Gson;
import com.lire.shop.converter.OrderConverter;
import com.lire.shop.dao.*;
import com.lire.shop.data.Constants;
import com.lire.shop.data.NullObjects;
import com.lire.shop.entity.User;
import com.lire.shop.model.vo.OrderVO;
import com.lire.shop.service.OrderService;
import com.lire.shop.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

@Tag(name = "订单管理")
@RestController
public class OrderController {

    @Autowired
    private Gson gson;

    @Autowired
    private OrderConverter orderConverter;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private WalletRepository walletRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ChecklistRepository checklistRepository;

    @Operation(summary = "查看个人所有订单", tags = {"订单管理", "01-test"})
    @ApiResponses({
            @ApiResponse(responseCode = "200",
                    content = {@Content(schema = @Schema(implementation = OrderVO.class), mediaType = "application/json")})
    })
    @GetMapping("/order/list")
    public String getOrders(HttpSession session) {
        User curUser = (User) session.getAttribute(Constants.CURRENT_USER);
        User user = userRepository.findByUsername(curUser.getUsername()).orElseGet(NullObjects::getUser);

        List<OrderVO> orders = orderRepository.findAllByUid(user.getUid())
                .stream()
                .filter(order -> !order.getOrderStatus().equals(Constants.ORDER_PAID_OFF))
                .map(order -> orderConverter.do2vo(order
                        , user, productRepository.findById(order.getPid())
                                .orElseGet(NullObjects::getProduct))
                ).collect(Collectors.toList());

        Map<String, Object> map = new HashMap<>();
        map.put("orders", orders);
        map.put("ordersCount", orders.size());
        return gson.toJson(map);
    }

    @Operation(summary = "选择一个商品id进行消费", tags = {"订单管理", "01-test"})
    @ApiResponses({
            @ApiResponse(responseCode = "200",
                    content = {@Content(schema = @Schema(implementation = OrderVO.class), mediaType = "application/json")})
    })
    @PostMapping("/order/product/{pid}")
    public String addOrder(@PathVariable Long pid, HttpSession session) {
        OrderVO orderVO = orderService.buyProduct(pid, session);
        Map<String, Object> map;
        // 购买失败处理
        if (Objects.isNull(orderVO)) {
            map = new HashMap<>();
            map.put("msg", "无法正常购买，请确认是否商品是否缺货并保证有足够金额购买。");
            return gson.toJson(map);
        }
        map = new HashMap<>();
        map.put("order", orderVO);
        return gson.toJson(orderVO);
    }

    @Operation(summary = "选择一个订单id进行退款", tags = {"订单管理", "01-test"})
    @ApiResponses({
            @ApiResponse(responseCode = "200",
                    content = {@Content(schema = @Schema(implementation = OrderVO.class), mediaType = "application/json")})
    })
    @PatchMapping("/order/{oid}/refund")
    public String refund(@PathVariable("oid") Long oid, HttpSession session) {
        OrderVO orderVO = orderService.refundProduct(oid, session);
        Map<String, Object> map;
        // 购买失败处理
        if (Objects.isNull(orderVO)) {
            map = new HashMap<>();
            map.put("msg", "请确认订单号是否正确，切记不要重复提交。");
            return gson.toJson(map);
        }
        map = new HashMap<>();
        map.put("order", orderVO);
        return gson.toJson(map);
    }
}
